package com.durian.base.frame.activity;

import android.content.Intent;
import android.view.KeyEvent;
import androidx.fragment.app.FragmentTransaction;
import com.durian.base.frame.easyrouter.EasyRouter;
import com.durian.base.frame.fragment.FragmentBind;
import com.durian.base.frame.titlebar.ISuperTitleBar;
import com.durian.base.utils.LogUtils;
import com.durian.base.utils.StringUtils;

/**
 * 说明：BindFragmentSupport
 * <p/>
 * 作者：Fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2020/08/14 21:57
 * <p/>
 * 版本：version 1.0
 */
public class BindFragmentSupport implements IBindFragment{

    private String fragmentName;
    private FragmentBind mFragment;

    @Override
    public void getIntentData(Intent intent) {
        if (intent.hasExtra(EasyRouter.KEY_FRAGMENT)){
            fragmentName = intent.getStringExtra(EasyRouter.KEY_FRAGMENT);
            if (StringUtils.isNotEmpty(fragmentName)){
                Object object = EasyRouter.build(fragmentName)
                        .withAll(intent.getExtras())
                        .navigation();
                if (object != null && object instanceof FragmentBind){
                    mFragment = (FragmentBind) object;
                }else {
                    LogUtils.e("this fragment must be extends FragmentBind!!!");
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mFragment != null){
            return mFragment.onKeyDown(keyCode,event);
        }
        return false;
    }


    @Override
    public ISuperTitleBar bindSuperTitleBar() {
        if (mFragment != null){
            return mFragment.bindSuperTitleBar();
        }
        return null;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mFragment != null){
            mFragment.onActivityResult(requestCode,resultCode,data);
        }
    }

    @Override
    public void onDestroy(ActivityFrame activityFrame) {
        if (mFragment != null){
            FragmentTransaction transaction = activityFrame.getSupportFragmentManager()
                    .beginTransaction();
            transaction.remove(mFragment);
            mFragment = null;
        }
    }

    public FragmentBind getFragment() {
        return mFragment;
    }
}
